package com.amtf.datafile2.core.std;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.amtf.datafile2.DataCatalog;
import com.amtf.datafile2.DataException;
import com.amtf.datafile2.DataFieldDefinition;
import com.amtf.datafile2.DataTable;
import com.amtf.datafile2.DataTableDefinition;

public abstract class StdDataCatalog<DT extends DataTable<DTD, DFD>, DTD extends DataTableDefinition<DFD>, DFD extends DataFieldDefinition> implements DataCatalog<DT, DTD, DFD> {

	private final Map<String, DT> dataTables = new HashMap<String, DT>();
	protected String name = "";

	// protected T defaultDefinition = null;

	public StdDataCatalog(String name) {
		this.name = name;
	}

	// public StdDataCatalog(String name, T defaultDefinition) {
	// this.name = name;
	// this.defaultDefinition = defaultDefinition;
	// }

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getDataTableCount() {
		return dataTables.size();
	}

	public List<DT> getDataTables() {
		List<DT> tbs = new ArrayList<DT>();
		tbs.addAll(dataTables.values());
		return tbs;
	}

	public DT getDataTable(int index) {
		return getDataTables().get(index);
	}

	public void setDataTable(String name, DT tableSet) {
		dataTables.put(name, tableSet);
	}

	public boolean isDataTableExists(String name) {
		return dataTables.get(name) != null;
	}

	public DT getDataTable(String name) {
		return dataTables.get(name);
	}

	public DT dropDataTable(String name) throws DataException {
		return dataTables.remove(name);
	}

	public void setDataTableDefinition(DTD definition) throws DataException {
		List<DT> list = this.getDataTables();
		for (DT dt : list) {
			dt.setDefinition(definition);
		}
	}

	public void setDataTableDefinition(String name, DTD definition) throws DataException {
		DT dt = this.getDataTable(name);
		if (dt != null) {
			dt.setDefinition(definition);
		}
	}

	public void close() {
		List<DT> list = this.getDataTables();
		for (DT dt : list) {
			dt.close();
		}
	}
}
